package com.kaiwukj.android.ufamily.mvp.ui.page.account.update;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerAccountComponent;
import com.kaiwukj.android.ufamily.di.module.AccountModule;
import com.kaiwukj.android.ufamily.mvp.helper.GlideEngine;
import com.kaiwukj.android.ufamily.mvp.http.entity.bean.JsonBean;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.UpdateUserInfoEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.UserInfoParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommunityResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.UserResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.account.AccountContract;
import com.kaiwukj.android.ufamily.utils.GetJsonDataUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zghl.mclient.client.ZghlMClient;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = ARouterUrlKt.PersonInfoUpdateUrl)
public class UserUpdateActivity extends BaseMvpActivity<UserUpdatePresenter> implements AccountContract.EditView {

    private static final int PICK_COMMUNITY = 101;

    private static final int NICKNAME_EDIT = 102;
    private static final int PHONE_EDIT = 103;
    private static final int SIGN_EDIT = 104;
    private static final int JOB_EDIT = 105;
    private static final int UPDATE_FACE = 106;
    private static final int PICK_ADDRESS = 107;

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_sign)
    TextView tvSign;
    @BindView(R.id.tv_area)
    TextView tvArea;
    @BindView(R.id.tv_job)
    TextView tvJob;
    @BindView(R.id.tv_community)
    TextView tvCommunity;
    @BindView(R.id.tv_face)
    TextView tvFace;

    private List<JsonBean> options1Items = new ArrayList();
    private List<List<String>> options2Items = new ArrayList<>();
    private List<List<List<String>>> options3Items = new ArrayList();

    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
    }

    @OnClick({R.id.container_avatar,
            R.id.container_phone,
            R.id.container_nickname,
            R.id.container_sex,
            R.id.container_sign,
            R.id.container_area,
            R.id.container_job,
            R.id.container_community,
            R.id.container_face})
    void onItemClick(View v) {
        switch (v.getId()) {
            case R.id.container_avatar:
                pickAvatar();
                break;
            case R.id.container_phone:
                break;
            case R.id.container_nickname:
                editNickname();
                break;
            case R.id.container_sex:
                pickSex();
                break;
            case R.id.container_sign:
                editSign();
                break;
            case R.id.container_area:
                //  start(EditMineAddressFragment.Companion.newInstance(null), PICK_ADDRESS);
                pickArea();
                break;
            case R.id.container_job:
                editJob();
                break;
            case R.id.container_community:
                pickCommunity();
                break;
            case R.id.container_face:
                /*ARouter.getInstance().build(ARouterUrlKt.ViseFaceActivityUrl)
                        .navigation(this, UPDATE_FACE);*/
                ARouter.getInstance().build(ARouterUrlKt.FacePrewRouterUrl).navigation();
                break;
        }
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerAccountComponent.builder()
                .appComponent(appComponent)
                .accountModule(new AccountModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_userinfo_update;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        tvTitle.setText("个人资料");
        initUI(getApp().getUserInfo());
        subscribe(Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
            emitter.onNext(initJsonData());
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(a -> {
                    LogUtils.d("----------onComplete----------");
                }));
    }

    private void initUI(UserResult result) {
        if (result == null) return;

        Glide.with(this)
                .load(result.getHeadImg())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(ivAvatar);
        tvNickname.setText(result.getNickName());
        tvPhone.setText(result.getPhone());
        tvSign.setText(result.getSignature());
        tvSex.setText(result.getGenderStr());
        tvArea.setText(result.getRegion());
        tvJob.setText(result.getIndustry());
        tvCommunity.setText(result.getLastCommunityName());
        tvFace.setText(ZghlMClient.getInstance().hasFace() ? "已采集" : "未采集");
    }

    private void pickAvatar() {
        RxPermissions rxPermissions = new RxPermissions(this);
        Disposable disposable = rxPermissions.request(Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(g -> {
                    if (g) {
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofImage())
                                .imageEngine(GlideEngine.createGlideEngine())
                                .isCompress(true)
                                .compressQuality(75)
                                .maxSelectNum(1)
                                .circleDimmedLayer(true)
                                .withAspectRatio(1, 1)
                                .isEnableCrop(true)
                                .theme(R.style.MyImagePickerStyle)
                                .forResult(new OnResultCallbackListener<LocalMedia>() {
                                    @Override
                                    public void onResult(List<LocalMedia> result) {
                                        String filePath;
                                        LocalMedia localMedia = result.get(0);
                                        if (localMedia.isCompressed()) {
                                            filePath = localMedia.getCompressPath();
                                        } else if (localMedia.isCut()) {
                                            filePath = localMedia.getCutPath();
                                        } else {
                                            filePath = localMedia.getPath();
                                        }
                                        // String filePath = result.get(0).getCompressPath();
                                        Glide.with(UserUpdateActivity.this)
                                                .load(filePath)
                                                .into(ivAvatar);
                                        mPresenter.updateAvatar(filePath);
                                        showLoading("正在处理...");

                                    }

                                    @Override
                                    public void onCancel() {

                                    }
                                });
                    }
                });
        subscribe(disposable);

    }

    private void editJob() {
        ARouter.getInstance().build(ARouterUrlKt.UserInfoEditUrl)
                .withInt("inputType", UserinfoEditActivity.TEXT)
                .withString("title", "编辑行业")
                .withString("hint", "请输入您的行业")
                .withString("text", getApp().getUserInfo().getIndustry())
                .withInt("maxCount", 8)
                .navigation(this, JOB_EDIT);
    }

    private void editNickname() {
        ARouter.getInstance().build(ARouterUrlKt.UserInfoEditUrl)
                .withInt("inputType", UserinfoEditActivity.TEXT)
                .withString("title", "编辑昵称")
                .withString("text", getApp().getUserInfo().getNickName())
                .withString("hint", "请输入新的昵称")
                .withInt("maxCount", 12)
                .navigation(this, NICKNAME_EDIT);
        ;
    }

    private void pickSex() {
        String[] sexArray = new String[]{"男", "女"};
        QMUIDialog.MenuDialogBuilder builder = new QMUIDialog.MenuDialogBuilder(this);
        builder.addItems(sexArray, (dialog, which) -> {
            tvSex.setText(sexArray[which]);
            UserInfoParams params = new UserInfoParams();
            params.setGender(which + 1);
            mPresenter.update(params);
            dialog.cancel();
        }).show();
    }

    private void editSign() {
        ARouter.getInstance().build(ARouterUrlKt.UserInfoEditUrl)
                .withInt("inputType", UserinfoEditActivity.TEXT)
                .withString("title", "编辑签名")
                .withString("text", getApp().getUserInfo().getTrueSignature())
                .withString("hint", "请输入新的个性签名")
                .withInt("maxCount", 50)
                .navigation(this, SIGN_EDIT);
    }

    private void pickCommunity() {
        ARouter.getInstance().build(ARouterUrlKt.CommunityUpdateUrl)
                .withInt("pickAction", 1)
                .navigation(this, PICK_COMMUNITY);
    }

    private void pickArea() {
        OptionsPickerView pickerView
                = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String c1 = options1Items.get(options1).getName();
            String c2 = options2Items.get(options1).get(options2);
            String c3 = options3Items.get(options1).get(options2).get(options3);
            String area = String.format("%s-%s-%s", c1, c2, c3);
            tvArea.setText(area);
            UserInfoParams params = getNewParams();
            params.setRegion(area);
            mPresenter.update(params);

        }).setTitleText(getString(R.string.mine_address_choice_area))
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .setDividerColor(ContextCompat.getColor(this, R.color.common_divide_line_color))
                .setContentTextSize(16)
                .setSubmitColor(ContextCompat.getColor(this, R.color.app_color_theme))
                .setCancelColor(ContextCompat.getColor(this, R.color.common_text_slight_color))
                .setSelectOptions(13, 0, 0)
                .setLineSpacingMultiplier(2.0f)
                .build();

        pickerView.setPicker(options1Items, options2Items, options3Items);
        pickerView.show();

    }

    private Integer initJsonData() {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        List<JsonBean> jsonBean = GsonUtils.fromJson(JsonData, GsonUtils.getListType(JsonBean.class));//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            List<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            List<List<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int j = 0; j < jsonBean.get(i).getCityList().size(); j++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(j).getName();
                cityList.add(cityName);//添加城市
                List<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(j).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        // mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS)
        return 1;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PICK_COMMUNITY:
                if (resultCode == RESULT_OK) {
                    if (data != null && data.getExtras() != null) {
                        CommunityResult extra = (CommunityResult) data.getExtras().getSerializable("data");
                        if (extra != null) {
                            //   reqParams
                            tvCommunity.setText(extra.getCommunityName());
                            mPresenter.updateCommunity(extra.getId());
                        }
                    }
                }
                break;
            case NICKNAME_EDIT:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String extra = data.getStringExtra("extra");
                        tvNickname.setText(extra);
                        UserInfoParams params = getNewParams();
                        params.setNickName(extra);
                        mPresenter.update(params);

                    }
                }
                break;
            case SIGN_EDIT:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String extra = data.getStringExtra("extra");
                        UserInfoParams params = getNewParams();
                        params.setSignature(extra);
                        mPresenter.update(params);
                        tvSign.setText(extra);
                    }
                }
                break;
            case JOB_EDIT:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String extra = data.getStringExtra("extra");
                        UserInfoParams params = getNewParams();
                        params.setIndustry(extra);
                        mPresenter.update(params);
                        tvJob.setText(extra);
                    }
                }
                break;
            case UPDATE_FACE:
                if (resultCode == RESULT_OK) {
                    tvFace.setText(ZghlMClient.getInstance().hasFace() ? "已采集" : "未采集");
                }
                break;
        }
    }

    private UserInfoParams getNewParams() {
        return new UserInfoParams();
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        showMessage("修改成功");
        EventBus.getDefault().post(new UpdateUserInfoEvent(UpdateUserInfoEvent.REQUEST));
    }

}
